/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package carrello.impl.controller.user;

import carrello.model.entities.User;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @author mepcotterell
 */
public class LogInCTRL {
    
   private static String getMD5Hash ( String password ) 
    {
        try {
            MessageDigest m = MessageDigest.getInstance("MD5");
            m.reset();
            m.update(password.getBytes());
            byte[] digest = m.digest();
            BigInteger bigInt = new BigInteger(1,digest);
            String hashtext = bigInt.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while(hashtext.length() < 32 ){
              hashtext = "0"+hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(SignUpCTRL.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }   
    public static String login (String username, String password ) {
        User u = (User)User.getUserByUserName(username);
        if ( u == null )
            return null;
        
        String md5 = getMD5Hash(password);
        if ( md5.compareTo(u.getPasswordHash()) == 0 )
        {
            return u.getRole();
        }
        
        return null;
    }
    
}
